package com.geoai.featstatusbar.flightcheck.custom

import kotlin.jvm.JvmOverloads
import android.annotation.SuppressLint
import android.content.Context
import android.view.MotionEvent
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.ScrollView
import com.geoai.featstatusbar.R

/**
 * 双滑块的bar
 */
class DoubleSeekBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    /**
     * 线条（进度条）的宽度
     */
    private val lineWidth: Int

    /**
     * 线条（进度条）的长度
     */
    private var lineLength = 400

    /**
     * 字所在的高度 100$
     */
    private var textHeight = 0

    /**
     * 游标 图片宽度
     */
    private val imageWidth: Int

    /**
     * 游标 图片高度
     */
    private val imageHeight: Int

    /**
     * 是否有刻度线
     */
    private val hasRule: Boolean

    /**
     * 左边的游标是否在动
     */
    private var isLeftCursorMoving = false

    /**
     * 右边的游标是否在动
     */
    private var isRightCursorMoving = false
    //    /**
    //     * 字的大小 100$
    //     */
    //    private int textSize;
    //    /**
    //     * 字的颜色 100$
    //     */
    //    private int textColor;
    /**
     * 两个游标内部 线（进度条）的颜色
     */
    private var rightColor = Color.BLUE

    /**
     * 两个游标外部 线（进度条）的颜色
     */
    private var leftColor = Color.BLUE

    /**
     * 刻度的颜色
     */
    private var ruleColor = Color.BLUE

    /**
     * 刻度上边的字 的颜色
     */
    private var ruleTextColor = Color.BLUE

    /**
     * 左边图标的图片
     */
    private var bitmapLeft: Bitmap?

    /**
     * 右边图标 的图片
     */
    private var bitmapRight: Bitmap?

    /**
     * 左边图标所在X轴的位置
     */
    private var leftCursorX = 0

    /**
     * 右边图标所在X轴的位置
     */
    private var rightCursorX = 0

    /**
     * 是否隐藏左边滑块
     */
    private var isLeftCursorHide = false

    /**
     * 是否隐藏右边滑块
     */
    private var isRightCursorHide = false

    /**
     * 图标（游标） 高度
     */
    private var bitmapHeight = 0

    /**
     * 图标（游标） 宽度
     */
    private var bitmapWidth = 0

    /**
     * 加一些padding 大小酌情考虑 为了我们的自定义view可以显示完整
     */
    private val paddingLeft = 10
    private val paddingRight = 10
    private val paddingTop = 10
    private val paddingBottom = 10

    /**
     * 线（进度条） 开始的位置
     */
    private var lineStart = 0

    /**
     * 线的Y轴位置
     */
    private var lineY = 0

    /**
     * 线（进度条）的结束位置
     */
    private var lineEnd = lineLength

    /**
     * 选择器的最大值
     */
    private var bigValue = 100

    /**
     * 选择器的最小值
     */
    private var smallValue = 0

    /**
     * 左滑块可滑动的最大值
     */
    private var leftCursorBigValue = 100

    /**
     * 左滑块可滑动的最小值
     */
    private var leftCursorSmallValue = 0

    /**
     * 右滑块可滑动的最大值
     */
    private var rightCursorBigValue = 100

    /**
     * 右滑块可滑动的最小值
     */
    private var rightCursorSmallValue = 0

    /**
     * 选择器的当前最小值
     */
    private var currentLeftRange = 0

    /**
     * 选择器的当前最大值
     */
    private var currentRightRange = 0

    /**
     * 单位 元
     */
    private var unit: String? = " "

    /**
     * 单位份数
     */
    private var equal = 20

    /**
     * 刻度单位 $
     */
    private var ruleUnit: String? = " "

    /**
     * 刻度上边文字的size
     */
    private var ruleTextSize = 20

    private var scrollView: ScrollView? = null

    /**
     * 刻度线的高度
     */
    private var ruleLineHeight = 20
    private var linePaint: Paint? = null
    private var bitmapPaint: Paint? = null
    private var textPaint: Paint? = null
    private val paintRule: Paint? = null
    private fun init() {
        /**游标的默认图 */
        if (bitmapLeft == null) {
            bitmapLeft = BitmapFactory.decodeResource(resources, android.R.mipmap.sym_def_app_icon)
        }
        if (bitmapRight == null) {
            bitmapRight = BitmapFactory.decodeResource(resources, android.R.mipmap.sym_def_app_icon)
        }
        /**游标图片的真实高度 之后通过缩放比例可以把图片设置成想要的大小 */
        bitmapHeight = bitmapLeft!!.height
        bitmapWidth = bitmapLeft!!.width

    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        postInvalidate()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val width = getMyMeasureWidth(widthMeasureSpec)
        val height = getMyMeasureHeight(heightMeasureSpec)
        setMeasuredDimension(width, height)
    }

    private fun getMyMeasureHeight(heightMeasureSpec: Int): Int {
        return paddingBottom + paddingBottom + bitmapHeight
    }

    private fun getMyMeasureWidth(widthMeasureSpec: Int): Int {
        val mode = MeasureSpec.getMode(widthMeasureSpec)
        var size = MeasureSpec.getSize(widthMeasureSpec)
//        size = if (mode == MeasureSpec.EXACTLY) {
//            size.coerceAtLeast(paddingLeft + paddingRight + bitmapWidth * 2)
//        } else {
//            //wrap content
//            val width = paddingLeft + paddingRight + bitmapWidth * 2
//            size.coerceAtMost(width)
//        }
        // match parent 或者 固定大小 此时可以获取线（进度条）的长度
//        lineLength = size - paddingLeft - paddingRight
        lineLength = size - bitmapWidth
        //线（进度条）的结束位置
        lineEnd = lineLength + bitmapWidth / 2
//        lineEnd = lineLength + paddingLeft + bitmapWidth / 2

        //线（进度条）的开始位置
        lineStart = bitmapWidth / 2
//        lineStart = paddingLeft + bitmapWidth / 2
        /**初始化两个游标的位置 */
        leftCursorX = seekbarValueToCoordX(currentLeftRange) + 1

        rightCursorX = seekbarValueToCoordX(currentRightRange) + 1
        //初始化 游标位置
        return size
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        // Y轴 坐标
        lineY = (height) / 2
        // 字所在高度 100$
        textHeight = lineY - bitmapHeight / 2 - 10
        //        //是否画刻度

        linePaint = Paint()
        //画内部线
        linePaint?.let {
            it.isAntiAlias = true
            it.strokeWidth = lineWidth.toFloat()
            it.color = rightColor
            it.strokeCap = Paint.Cap.ROUND
            canvas.drawLine(
                leftCursorX.toFloat(),
                lineY.toFloat(),
                rightCursorX.toFloat(),
                lineY.toFloat(),
                it
            )
        }

        linePaint?.let {
            it.color = leftColor
            it.strokeCap = Paint.Cap.ROUND
            canvas.drawLine(
                lineStart.toFloat(),
                lineY.toFloat(),
                leftCursorX.toFloat(),
                lineY.toFloat(),
                it
            )
        }

        //画 外部线
        linePaint?.let {
            it.color = context.resources.getColor(R.color.base_grey)
            it.strokeCap = Paint.Cap.ROUND
            canvas.drawLine(
                rightCursorX.toFloat(),
                lineY.toFloat(),
                lineEnd.toFloat(),
                lineY.toFloat(),
                it
            )
        }

        //画游标
        if (bitmapPaint == null) {
            bitmapPaint = Paint()
        }

        if(!isLeftCursorHide){
            bitmapLeft?.let {
                canvas.drawBitmap(
                    it,
                    (leftCursorX - bitmapWidth / 2).toFloat(),
                    (lineY - bitmapHeight / 2).toFloat(),
                    bitmapPaint
                )
            }
        }

        if(!isRightCursorHide){
            bitmapRight?.let {
                canvas.drawBitmap(
                    it,
                    (rightCursorX - bitmapWidth / 2).toFloat(),
                    (lineY - bitmapHeight / 2).toFloat(),
                    bitmapPaint
                )
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //事件机制
        super.onTouchEvent(event)
        val nowX = event.x

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                parent.requestDisallowInterceptTouchEvent(true)

//                按下 在左边游标上
                nowX - leftCursorX
                isLeftCursorMoving = Math.abs(nowX - leftCursorX) < bitmapWidth / 2
                //按下 在右边游标上
                isRightCursorMoving = Math.abs(nowX - rightCursorX) < bitmapWidth / 2
            }
            MotionEvent.ACTION_MOVE ->      {           //左边游标是运动状态
                //当前 X坐标在线上 且在右边游标的左边
                if (isLeftCursorMoving && nowX <= rightCursorX - bitmapWidth / 2 && nowX >= lineStart - bitmapWidth / 2) {
                    leftCursorX = if(nowX < seekbarValueToCoordX(leftCursorSmallValue))
                        seekbarValueToCoordX(leftCursorSmallValue)+1
                    else if(nowX > seekbarValueToCoordX(leftCursorBigValue))
                        seekbarValueToCoordX(leftCursorBigValue)
                    else
                        nowX.toInt()

                    if (leftCursorX < lineStart) {
                        leftCursorX = lineStart
                    }
                    updateRange(false)
                    //更新进度
                    postInvalidate()
                }
                //当前 X坐标在线上 且在左边游标的右边
                if (isRightCursorMoving && nowX >= leftCursorX + bitmapWidth / 2 && nowX <= lineEnd + bitmapWidth / 2) {
                    rightCursorX = if(nowX < seekbarValueToCoordX(rightCursorSmallValue))
                        seekbarValueToCoordX(rightCursorSmallValue)+1
                    else if(nowX > seekbarValueToCoordX(rightCursorBigValue))
                        seekbarValueToCoordX(rightCursorBigValue)
                    else
                        nowX.toInt()

                    if (rightCursorX > lineEnd) {
                        rightCursorX = lineEnd
                    }
                    updateRange(false)
                    //更新进度
                    postInvalidate()
                }
            }
            MotionEvent.ACTION_UP -> {
                parent.requestDisallowInterceptTouchEvent(false)

                updateRange(true)

                isRightCursorMoving = false
                isLeftCursorMoving = false
            }
            else -> {}
        }
        return true
    }

    private fun updateRange(isActionFinish: Boolean) {
        //当前 左边游标数值
        val leftRange = coordXToSeekbarValue(leftCursorX.toFloat())
        val rightRange = coordXToSeekbarValue(rightCursorX.toFloat())

        if(leftRange == currentLeftRange && rightRange == currentRightRange && !isActionFinish)
            return

        currentLeftRange = leftRange
        //当前 右边游标数值
        currentRightRange = rightRange

        //接口 实现值的传递
        onRangeListener?.onRange(currentLeftRange, currentRightRange, isActionFinish)
    }

    /**
     * 获取当前值
     */
    private fun coordXToSeekbarValue(range: Float): Int {
        return ((range - lineStart) * (bigValue - smallValue) / lineLength + smallValue).toInt()
    }

    /**
     * 获取当前值
     */
    private fun seekbarValueToCoordX(value: Int): Int {
        return (value - smallValue) * lineLength / (bigValue - smallValue) + lineStart
    }

    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    /**
     * 写个接口 用来传递最大最小值
     */
    interface OnRangeListener {
        fun onRange(low: Int, big: Int,isActionFinish: Boolean)
    }

    private var onRangeListener: OnRangeListener? = null

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.DoubleSlideSeekBar)

        isRightCursorHide = typedArray.getBoolean(R.styleable.DoubleSlideSeekBar_rightCursorHide, false)
        isLeftCursorHide = typedArray.getBoolean(R.styleable.DoubleSlideSeekBar_leftCursorHide, false)

        rightColor = typedArray.getColor(R.styleable.DoubleSlideSeekBar_rightColor, Color.YELLOW)
        leftColor = typedArray.getColor(R.styleable.DoubleSlideSeekBar_leftColor, Color.RED)
        lineWidth = typedArray.getDimension(
            R.styleable.DoubleSlideSeekBar_lineHeight,
            dip2px(getContext(), 10f).toFloat()
        ).toInt()
        bitmapLeft = BitmapFactory.decodeResource(
            resources,
            typedArray.getResourceId(R.styleable.DoubleSlideSeekBar_leftCursorImg, 0)
        )
        bitmapRight = BitmapFactory.decodeResource(
            resources,
            typedArray.getResourceId(R.styleable.DoubleSlideSeekBar_rightCursorImg, 0)
        )
        imageHeight = Math.max(bitmapRight?.height!!, bitmapLeft?.height!!)
        imageWidth = Math.max(bitmapRight?.width!!, bitmapLeft?.width!!)
        hasRule = typedArray.getBoolean(R.styleable.DoubleSlideSeekBar_hasRule, false)
        ruleColor = typedArray.getColor(R.styleable.DoubleSlideSeekBar_ruleColor, Color.BLUE)
        ruleTextColor =
            typedArray.getColor(R.styleable.DoubleSlideSeekBar_ruleTextColor, Color.BLUE)
        unit = typedArray.getString(R.styleable.DoubleSlideSeekBar_unit)
        equal = typedArray.getInt(R.styleable.DoubleSlideSeekBar_equal, 10)
        ruleUnit = typedArray.getString(R.styleable.DoubleSlideSeekBar_ruleUnit)
        ruleTextSize = typedArray.getDimensionPixelSize(
            R.styleable.DoubleSlideSeekBar_ruleTextSize, TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 16f, resources.displayMetrics
            ).toInt()
        )
        ruleLineHeight = typedArray.getDimension(
            R.styleable.DoubleSlideSeekBar_ruleLineHeight,
            dip2px(getContext(), 10f).toFloat()
        ).toInt()
        bigValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_bigValue, 100)
        smallValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_smallValue, 0)

        leftCursorBigValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_leftCursorBigValue, bigValue)
        leftCursorSmallValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_leftCursorSmallValue, smallValue)

        rightCursorBigValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_rightCursorBigValue, bigValue)
        rightCursorSmallValue = typedArray.getInteger(R.styleable.DoubleSlideSeekBar_rightCursorSmallValue, smallValue)

        currentLeftRange = leftCursorSmallValue
        currentRightRange = rightCursorSmallValue

        typedArray.recycle()
        init()
    }

    fun setOnRangeListener(onRangeListener: OnRangeListener?) {
        this.onRangeListener = onRangeListener
    }

    fun refreshDoubleSeekBarSchedule(leftValue: Int, rightValue: Int) {
        if (leftValue < smallValue || rightValue <= leftValue || rightValue > bigValue) return
    }

    fun setLeftCursorValue(value: Int){
        currentLeftRange = value
        leftCursorX = seekbarValueToCoordX(currentLeftRange)

        postInvalidate()
    }

    fun setRightCursorValue(value: Int){
        currentRightRange = value
        rightCursorX = seekbarValueToCoordX(currentRightRange)

        postInvalidate()
    }
}